import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';

import { Input } from '../../components/input';
import { PasswordInput } from '../../components/input/password';
import { useRegisterMutation } from '../../generated/graphql';

import './index.css';

interface Props {}

export function RegisterPage({}: Props) {
  const history = useHistory();
  const [userName, setUserName] = useState('');
  const [password, setPassword] = useState('');
  const [passwordRepeat, setPasswordRepeat] = useState('');
  const [register, registerResult] = useRegisterMutation({
    notifyOnNetworkStatusChange: true,
    onCompleted(data) {
      alert('注册成功！');
      history.push('/login');
    },
    onError(e) {
      alert(e);
    }
  });
  return (
    <div className="page">
      <div className="register">
        <p className="registerTitle">用户注册</p>
        <div className="hr" />
        <p className="registerItem">
          <div className="registerDescribe">账号</div>
          <Input
            onChange={(e) => {
              setUserName(e.currentTarget.value);
            }}
            className="registerInput"
            placeholder="请输入账号"
          />
        </p>
        <p className="registerItem ">
          <div className="registerDescribe">密码</div>
          <PasswordInput
            onChange={(e) => {
              setPassword(e.currentTarget.value);
            }}
            className="registerInput"
            placeholder="请输入密码"
          />
        </p>
        <p className="registerItem">
          <div className="registerDescribe">确认密码</div>
          <PasswordInput
            onChange={(e) => {
              setPasswordRepeat(e.currentTarget.value);
            }}
            className="registerInput"
            placeholder="请再次输入密码"
          />
        </p>
        <div className="hr" />
        <button
          className="registerButton"
          onClick={() => {
            if (password !== passwordRepeat) {
              alert('两次输入密码不一致！');
              return;
            }
            register({
              variables: {
                userName,
                password
              }
            });
          }}
        >
          提交
        </button>
      </div>
    </div>
  );
}
